/*
 * Name: Joon Ho Cho
 * Date: 10/24/2008
 * Course: 15-437
 */
package scheduler.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.mybeans.dao.DAOException;
import org.mybeans.forms.FormBeanFactory;

import scheduler.databean.User;
import scheduler.formbean.LoginForm;
import scheduler.model.BookmarkDao;
import scheduler.model.Model;
import scheduler.model.UserDao;


public class LoginAction extends Action {
	private static FormBeanFactory<LoginForm> formBeanFactory =
		FormBeanFactory.getInstance(LoginForm.class,"<>\"");

	private BookmarkDao bookmarkDao;
	private UserDao  userDAO;

	public LoginAction(Model model) {
		bookmarkDao = model.getBookmarkDao();
		userDAO  = model.getUserDao();
	}

	public String getName() { return "login.do"; }
    
    public String perform(HttpServletRequest request) {
        try {
			List<String> errors = new ArrayList<String>();
            request.setAttribute("errors",errors);

            request.setAttribute("registeredUsers", userDAO.getAll());
	    	User user = (User) request.getSession(true).getAttribute("user");
	    	if (user != null) {
	    		errors.add("You are already logged in.");

		        request.setAttribute("bookmarks", null);
		        request.setAttribute("bookmarks", bookmarkDao.getBookmarksForUser(user.getUserName()));
	    		return "manage.jsp";
	    	}

			LoginForm form = formBeanFactory.create(request);
			request.setAttribute("form",form);

			if (!form.isPresent()) return "login.jsp";

	    	errors.addAll(form.getValidationErrors());
	    	if (errors.size() > 0) return "login.jsp";
	    	
	    	user = userDAO.getUserByName(form.getUserName());
	    	if (user == null) {
	    		errors.add("Username invalid");
	    		return "login.jsp";
	    	}
	    	
	    	if (!user.checkPassword(form.getPassword())) {
	    		errors.add("Incorrect password");
	    		return "login.jsp";
	    	}
	    	
	    	request.getSession(true).setAttribute("user",user);
	    	
	    	if (form.getRedirect().length() > 0) {
	    		return form.getRedirect();
	    	}
	    	request.setAttribute("bookmarks", null);
	        request.setAttribute("bookmarks", bookmarkDao.getBookmarksForUser(user.getUserName()));

	    	return "manage.jsp";
        } catch (DAOException e) {
        	e.printStackTrace();
        	request.setAttribute("dbError",e.getMessage());
        	return "db-error.jsp";
		}
		
    }
}
